import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home'},
  // 导航页
  { path: '/', name: 'Index', component: Index, meta: {isPublic: true},
    children: [
      // 首页
      { path: '/home', name: 'Home', component: () => import('../views/Home.vue'),
        meta: {isPublic:true, isKeep:true}},
      // 我的页
      { path: '/my', name: 'My', component: () => import('../views/My.vue'),
        meta: {}, }
    ]
  },
  // 搜索页
  { path: '/search', name: 'Search', component: () => import('../views/Search.vue'),
    meta: {isPublic: true}},
  // 个人资料编辑页
  { path: '/edit', name: 'Edit', component: () => import('../views/Edit.vue')},
  // 设置页
  { path: '/setting', name: 'Setting', component: () => import('../views/Setting.vue')},
  // 登录页
  { path: '/login', name: 'Login', component: () => import('../views/Login.vue'),
    meta: {isPublic: true}, },
  // 视频发布页
  { path: '/publish', name: 'Publish', component: () => import('../views/Publish.vue')},
  // 视频播放列表页
  { path: '/play', name: 'PlayList', component: () => import('../views/PlayList.vue'),
    meta: {isPublic: true}, props:true},
  // 账号验证
  { path: '/verify', name: 'Verify', component: () => import('../views/Verify.vue'),meta: {isPublic:true}},
  // 设置密码
  { path: '/update/pwd', name: 'ChangePwd', component: () => import('../views/ChangePwd.vue')},
  // 更换手机号
  { path: '/update/phone', name: 'ChangePhone', component: () => import('../views/ChangePhone.vue')},
  // 公示：用户协议、隐私政策、关于我们
  { path: '/notice', name: 'Notice', component: () => import('../views/Notice.vue'), meta: {isPublic:true}},
  // 作家主页
  { path: '/author/:id', name: 'Author', component: () => import('../views/Author.vue'),
    props:true, meta: {isPublic:true}},
]

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition){
    return {x: 0, y: 0}
  }
})

router.beforeEach((to, from, next)=>{
  if(!to.meta.isPublic && !localStorage.getItem('token')){
    from.path=='/home'? localStorage.setItem('goto',from.path) : localStorage.setItem('goto',to.path)
    next('/login')
  }else{
    next()
  }
})

export default router
